package com.biz.primus.ms.promotion.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.bean.BaseRedisObject;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.common.utils.ValueUtils;
import java.io.Serializable;

/**
 * @author david-liu
 */
public abstract class BasePromotionProductRedisDao<T extends BaseRedisObject<ID>, ID extends Serializable> extends CrudRedisDao<T, ID> {
    public T getPromotionProductRo(ID id) {
        return super.findOne(id);
    }

    /**
     * 更改活动商品的库存(扣减/补偿)
     *
     * @param promotionId 活动ID
     * @param productId 商品ID
     * @param quantity 数量
     */
    public Boolean changePromotionProductStock(Long promotionId, Long productId, Integer quantity) {
        if (ValueUtils.getValue(quantity) >= 0) {
            super.hincrBy(super.getHashKey(String.format("%s_%s", promotionId, productId)), RedisUtil.toByteArray("remainQuantity"), (long) quantity);
            return true;
        } else {
            Long seckillQuantity = super.hincrBy(super.getHashKey(String.format("%s_%s", promotionId, productId)), RedisUtil.toByteArray("remainQuantity"), (long) quantity);
            if (seckillQuantity > 0) {
                return true;
            } else {
                super.hincrBy(super.getHashKey(String.format("%s_%s", promotionId, productId)), RedisUtil.toByteArray("remainQuantity"), (long) -quantity);
                return false;
            }
        }
    }
}
